import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {Observable} from 'rxjs';

/**
 * 定义请求项类型
 */
interface HttpOptions {
  observe?: 'body';
  responseType?: 'json';
  reportProgress?: boolean;
  withCredentials?: boolean;
  headers?: HttpHeaders | { [header: string]: string | string[] };
  params?: HttpParams | { [param: string]: string | string[] };
}

@Injectable({
  providedIn: 'root'
})
export class HttpService {

  constructor(private http: HttpClient) {
  }

  get<T>(url: string, data?: any): Observable<T> {
    const httpOptions: HttpOptions = {
      headers: (new HttpHeaders()).set('Content-Type', 'application/json')
    };
    httpOptions.params = this.getHttpParams(data);
    return this.http.get<T>(url, httpOptions);
  }

  /**
   * Request Payload 方式提交数据
   */
  postBody<T>(url: string, body: any): Observable<T> {
    const httpOptions: HttpOptions = {
      headers: (new HttpHeaders()).set('Content-Type', 'application/json')
    };
    return this.http.post<T>(url, body, httpOptions);
  }

  /**
   * From Data 方式提交数据
   */
  postForm<T>(url: string, formData: any): Observable<T> {
    const httpOptions: HttpOptions = {
      headers: (new HttpHeaders()).set('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
    };
    // httpOptions.params = this.getHttpParams(formData);
    return this.http.post<T>(url, this.getHttpParams(formData), httpOptions);
  }

  /**
   * Query String Parameters 方式提交数据
   */
  postUrl<T>(url: string, urlData: any): Observable<T> {
    const httpOptions: HttpOptions = {
      headers: (new HttpHeaders()).set('Content-Type', 'application/json')
    };
    httpOptions.params = this.getHttpParams(urlData);
    return this.http.post<T>(url, {}, httpOptions);
  }

  /**
   * 封装请求数据
   */
  private getHttpParams(data: any): HttpParams {
    let httpParams = new HttpParams();
    if (data) {
      Object.keys(data).forEach(k => {
        if (data[k]) {
          httpParams = httpParams.set(k, data[k]);
        }
      });
    }
    return httpParams;
  }
}
